package com.train.mgr.modules.biz.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.train.common.enums.LoginTypeEnum;
import com.train.common.enums.ProjectTypeEnum;
import com.train.common.exception.BusinessException;
import com.train.common.model.PageResult;
import com.train.common.model.R;
import com.train.mgr.config.redis.RedisUtil;
import com.train.mgr.config.secrity.components.TrainAuthenticationToken;
import com.train.mgr.modules.biz.dto.request.CustQueryReqDTO;
import com.train.mgr.modules.biz.dto.request.CustReqDTO;
import com.train.mgr.modules.biz.dto.response.CustDetailRespDTO;
import com.train.mgr.modules.biz.dto.response.CustListRespDTO;
import com.train.mgr.modules.biz.entity.Customer;
import com.train.mgr.modules.biz.service.CustomerService;
import com.train.mgr.modules.system.dto.request.groups.Insert;
import com.train.mgr.modules.system.dto.request.groups.Update;
import com.train.mgr.modules.system.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author cxg
 * @desc 用户授权
 * @date 2023/02/01 16:32
 **/
@RestController
@Slf4j
@RequestMapping("/v1/customer")
@Api( tags = "企业管理[运营端]")
@RequiredArgsConstructor
public class CustomerController {

    private final CustomerService customerService;

    private final RedisUtil redisUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/quick_login/{id}")
    @ApiOperation("客户快速登录")
    public R<String> quickLogin(@PathVariable(name = "id") Long id) {
        User user = customerService.findUserByCustId(id);
        Integer userType = Integer.parseInt(user.getUserType());
        String token = IdUtil.simpleUUID();
        TrainAuthenticationToken unauthenticated =new TrainAuthenticationToken(user.getUsername(), user.getOriginalPwd(),userType,null,token, LoginTypeEnum.USERNAMELOGIN);
        TrainAuthenticationToken authenticate = null;
        try {
            authenticate = (TrainAuthenticationToken)authenticationManager.authenticate(unauthenticated);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
        } catch (AuthenticationException e) {
            log.error("error:" + e.getMessage());
            throw new BusinessException(" e.getMessage())～");
        }
        redisUtil.set(token,authenticate.getUserId(),60*60*24);
        return R.succeed(token,"客户快速登录成功");
    }


    @PostMapping("/add")
    @ApiOperation("新增客户")
    public R<Boolean> add(@RequestBody @Validated(Insert.class) CustReqDTO body) {
        return R.succeed(customerService.add(body));
    }

    @GetMapping("/project_list")
    @ApiOperation("授权功能")
    public R<Map<Integer, String>> projectList() {
        return R.succeed(ProjectTypeEnum.toCodeRemarkMap());
    }

    @PostMapping("/update")
    @ApiOperation("修改客户")
    public R<Boolean> update(@RequestBody @Validated(Update.class) CustReqDTO body) {
        return R.succeed(customerService.update(body));
    }

    @PostMapping("/delete")
    @ApiOperation("删除企业")
    public R<Boolean> delete(@RequestBody List<String> ids) {
        log.info("删除企业：{}", ids);
        UpdateWrapper<Customer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", 1);
        updateWrapper.in("id", ids);
        customerService.update(updateWrapper);
        return R.succeed("操作成功");
    }

    @GetMapping("{id}")
    @ApiOperation("查看企业")
    public R<CustDetailRespDTO> get(@PathVariable(name = "id") Long id) {
        return R.succeed(customerService.findById(id));
    }

    @PostMapping("/page")
    @ApiOperation("企业列表")
    public R<PageResult<CustListRespDTO>> page(@RequestBody CustQueryReqDTO params) {
         return R.succeed(customerService.page(params));
    }

    @PostMapping("/setCheckMode")
    @ApiOperation("审核模式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerId", value = "企业ID", dataType = "Long", required = true),
            @ApiImplicitParam(name = "checkMode", value = "员工账号审核模式（0-需审核，1-无需审核）", dataType = "Integer", required = true)
    })
    public R<Boolean> setEmpCheckMode(@RequestParam(name = "customerId", required = true) Long customerId,
                                      @RequestParam(name = "checkMode", required = true) Integer checkMode) {
        Boolean result = customerService.setEmpCheckMode(customerId,checkMode);
        return R.succeed(result);
    }
    @GetMapping("/check/code")
    @ApiOperation("校验企业编码是否存在")
    @ApiImplicitParam(name = "code", value = "企业编码", dataType = "String", required = true)
    public R<Boolean> checkCustomerCode(@RequestParam(name = "code") String code) {
        Boolean exists = customerService.checkCustomerCode(code);
        return R.succeed(exists);
    }

}
